package com.ruoyi.common.utils;

import com.aliyun.oss.OSSClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.FileNotFoundException;
import java.io.InputStream;

@Component
public class OssUtils {

    private static final Logger log = LoggerFactory.getLogger(OssUtils.class);
    private static String ENDPOINT = "http://oss-cn-beijing.aliyuncs.com";
    private static String ACCESS_KEY_ID = "LTAI5tBR3LRkEJn4p3wWqKXh";
    private static String ACCESS_KEY_SECRET = "rj03dE0IEXfrRLUbntZnxlDhrAG7po";

    private static OSSClient ossClient;

    @PostConstruct
    private void init() {
        ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    }

    public void putObject(String bucket, String key, InputStream input) {
        ossClient.putObject(bucket, key, input);
    }

    public void deleteObject(String bucket, String key) {
        ossClient.deleteObject(bucket, key);
    }

    public String generateKey(String fileName){
        String prefix = fileName.substring(0, fileName.lastIndexOf("."));
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        return prefix + "_" + DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS) + suffix;
    }

    public static void main(String[] args) throws FileNotFoundException {

        System.out.println(new OssUtils().generateKey("aa123.txt1"));

        /*String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAI5tBR3LRkEJn4p3wWqKXh";
        String accessKeySecret = "rj03dE0IEXfrRLUbntZnxlDhrAG7po";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 创建Bucket
        //CreateBucketRequest createBucketRequest = new CreateBucketRequest("freight-test-2");
        //ossClient.createBucket(createBucketRequest);

        InputStream inputStream = new FileInputStream("D:\\test1.txt");
        // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        ossClient.putObject("freight-test-2", "test1/test1.txt", inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();*/


    }
}
